<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>第1课互联网发展靠创新-练习</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>第1课互联网发展靠创新-练习</h1>
        </div>
        <div class="card"></div>
    </div>

    <script>
        // 题库，含多项选择题示例
        const questions = [
            {
                type: 'judge',
                section: '一、判断题（共5题）',
                items: [
                    {
                        text: '互联网在形成阶段实现了TCP/IP协议的标准化。',
                        options: [{ value: 'A', label: '正确' }, { value: 'B', label: '错误' }],
                        answer: 'B',
                        explanation: 'TCP/IP协议标准化是在互联阶段实现的，形成阶段的标志是阿帕网（ARPA Net）诞生。'
                    },
                    // ... 其余判断题 ...
                ]
            },
            {
                type: 'choice',
                section: '二、选择题（共15题）',
                items: [
                    {
                        text: '互联网发展的哪个阶段实现了TCP/IP协议标准化？',
                        options: [
                            { value: 'A', label: '诞生阶段' },
                            { value: 'B', label: '形成阶段' },
                            { value: 'C', label: '互联阶段' },
                            { value: 'D', label: '高速网络阶段' }
                        ],
                        answer: 'C',
                        explanation: '在互联阶段，TCP/IP协议实现标准化，成为互联网的基础协议。'
                    },
                    // ... 其余选择题 ...
                ]
            },
            {
                type: 'multi',
                section: '三、多项选择题',
                items: [
                    {
                        text: '下列哪些属于互联网基础协议？（多选）',
                        options: [
                            { value: 'A', label: 'TCP' },
                            { value: 'B', label: 'IP' },
                            { value: 'C', label: 'HTTP' },
                            { value: 'D', label: 'SMTP' }
                        ],
                        answer: ['A', 'B', 'D'],
                        explanation: 'TCP、IP、SMTP 都是互联网基础协议，HTTP 属于应用层协议。'
                    }
                ]
            }
        ];

        // 自动生成 number 字段
        (function autoNumberQuestions() {
            let num = 1;
            questions.forEach(section => {
                section.items.forEach(item => {
                    item.number = num++;
                });
            });
        })();

        // 生成题目HTML
        function renderQuestions() {
            const card = document.querySelector('.card');
            card.innerHTML = `
                <div class="progress">
                    进度：<span id="current">0</span>/${questions.reduce((sum, sec) => sum + sec.items.length, 0)}题
                </div>
                <div id="questions"></div>
                <div class="btn-group">
                    <button class="btn btn-primary" id="submit">提交答案</button>
                    <button class="btn btn-secondary" id="reset">重置</button>
                </div>
                <div class="result" id="result">
                    <h3 class="correct">答题完成！共答对 <span id="score">0</span> 题</h3>
                </div>
            `;
            const questionsDiv = card.querySelector('#questions');
            let html = '';
            questions.forEach(section => {
                html += `<div class="question-section"><h2 class="section-title">${section.section}</h2>`;
                section.items.forEach(item => {
                    let name;
                    if (section.type === 'judge') {
                        name = `t${item.number}`;
                    } else if (section.type === 'choice') {
                        name = `q${item.number}`;
                    } else if (section.type === 'multi') {
                        name = `m${item.number}`;
                    }
                    const inputType = section.type === 'multi' ? 'checkbox' : 'radio';
                    html += `
                        <div class="question">
                            <p><span class="question-number">${item.number}</span>${item.text}</p>
                            <div class="options">
                                ${item.options.map(opt => `
                                    <div class="option">
                                        <input type="${inputType}" name="${name}" value="${opt.value}" id="${name}-${opt.value}">
                                        <label for="${name}-${opt.value}">${opt.value}. ${opt.label}</label>
                                    </div>
                                `).join('')}
                            </div>
                            <div class="correct-answer" id="ans-${name}"></div>
                            <div class="explanation" id="exp-${name}">解析：${item.explanation}</div>
                        </div>
                    `;
                });
                html += '</div>';
            });
            questionsDiv.innerHTML = html;
        }
        renderQuestions();

        // 生成正确答案映射
        const correctAnswers = {};
        questions.forEach(section => {
            section.items.forEach(item => {
                let name;
                if (section.type === 'judge') {
                    name = `t${item.number}`;
                } else if (section.type === 'choice') {
                    name = `q${item.number}`;
                } else if (section.type === 'multi') {
                    name = `m${item.number}`;
                }
                correctAnswers[name] = item.answer;
            });
        });

        // 获取DOM元素
        const card = document.querySelector('.card');
        const currentEl = card.querySelector("#current");
        const scoreEl = card.querySelector("#score");
        const resultEl = card.querySelector("#result");

        // 跟踪已答题数量
        let answeredCount = 0;

        // 更新进度
        function updateProgress() {
            let total = Object.keys(correctAnswers).length;
            let count = 0;
            for (const name of Object.keys(correctAnswers)) {
                const inputType = Array.isArray(correctAnswers[name]) ? 'checkbox' : 'radio';
                if (inputType === 'radio') {
                    if (card.querySelector(`input[name="${name}"]:checked`)) count++;
                } else {
                    if (card.querySelectorAll(`input[name="${name}"]:checked`).length > 0) count++;
                }
            }
            currentEl.textContent = count;
        }

        // 验证答案并计算得分
        function validateAnswers() {
            let score = 0;
            for (const [question, answer] of Object.entries(correctAnswers)) {
                const ansEl = card.querySelector(`#ans-${question}`);
                const expEl = card.querySelector(`#exp-${question}`);
                // 多选题
                if (Array.isArray(answer)) {
                    const selected = Array.from(card.querySelectorAll(`input[name="${question}"]:checked`)).map(i => i.value).sort();
                    const correct = answer.slice().sort();
                    ansEl.textContent = `正确答案：${correct.join('、')}`;
                    expEl.classList.add('show');
                    // 标记正确选项
                    correct.forEach(val => {
                        const opt = card.querySelector(`input[name="${question}"][value="${val}"]`);
                        if (opt) opt.closest('.option').classList.add('correct');
                    });
                    // 标记错误选项
                    selected.forEach(val => {
                        if (!correct.includes(val)) {
                            const opt = card.querySelector(`input[name="${question}"][value="${val}"]`);
                            if (opt) opt.closest('.option').classList.add('incorrect');
                        }
                    });
                    // 判分
                    if (selected.length && selected.join(',') === correct.join(',')) {
                        score++;
                    }
                } else {
                    // 单选/判断题
                    const selectedOption = card.querySelector(`input[name="${question}"]:checked`);
                    ansEl.textContent = `正确答案：${answer}`;
                    expEl.classList.add('show');
                    const correctOption = card.querySelector(`input[name="${question}"][value="${answer}"]`);
                    if (correctOption) correctOption.closest('.option').classList.add('correct');
                    if (selectedOption) {
                        if (selectedOption.value === answer) {
                            score++;
                        } else {
                            selectedOption.closest('.option').classList.add('incorrect');
                        }
                    }
                }
            }
            scoreEl.textContent = score;
            resultEl.classList.add('show');
        }

        // 重置答题状态
        function resetQuiz() {
            // 清除选中状态和样式
            card.querySelectorAll('input[type="radio"],input[type="checkbox"]').forEach(input => {
                input.checked = false;
                const optionEl = input.closest('.option');
                optionEl.classList.remove('correct', 'incorrect');
            });
            // 隐藏正确答案、解析和结果
            Object.keys(correctAnswers).forEach(question => {
                const ansEl = card.querySelector(`#ans-${question}`);
                const expEl = card.querySelector(`#exp-${question}`);
                ansEl.textContent = "";
                expEl.classList.remove('show');
            });
            resultEl.classList.remove('show');
            updateProgress();
        }

        // 监听选项变化
        card.addEventListener('change', function (e) {
            if (e.target.type === 'radio' || e.target.type === 'checkbox') {
                updateProgress();
            }
        });

        // 监听提交按钮
        card.querySelector("#submit").addEventListener('click', validateAnswers);
        // 监听重置按钮
        card.querySelector("#reset").addEventListener('click', resetQuiz);
        // 初始化进度
        updateProgress();
    </script>
</body>

</html>